﻿
using System.ComponentModel;
using System.Data;
using System.Reflection;
namespace System
{
    public static partial class Utility
    {
        public static DataTable GetEnumAsDataTable(this Array pEnum)
        {
            return GetEnumAsDataTable(pEnum, 0);
        }

        public static DataTable GetEnumAsDataTable(this Array pEnum, SortingDirection pSortDirection)
        {
            DataTable oDt = new DataTable();
            oDt.Columns.Add("Text");
            oDt.Columns.Add("Value");
            oDt.Columns.Add("Description");
            oDt.TableName = "ENUM";

            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = oDt.Columns["Value"];
            oDt.PrimaryKey = PrimaryKeyColumns;

            foreach (var item in pEnum)
            {
                string itemText = item.ToString();
                string itemValue = Convert.ToInt32(item).ToString();
                string itemDescription = "";
                FieldInfo fi = item.GetType().GetField(item.ToString());
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                itemDescription = (attributes.Length > 0) ? attributes[0].Description : item.ToString();

                DataRow oRw = oDt.NewRow();
                oRw["Text"] = itemText;
                oRw["Value"] = itemValue;
                oRw["Description"] = itemDescription;
                oDt.Rows.Add(oRw);
            }

            if (pSortDirection != 0) oDt = oDt.FilterDataTable(string.Empty, string.Format("Text {0}", pSortDirection.ToString()));
            return oDt;
        }

        public static string GetEnumDescription(this Enum pEnumItem)
        {
            Type type = pEnumItem.GetType();
            MemberInfo[] memInfo = type.GetMember(pEnumItem.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return pEnumItem.ToString();
        }

        public static T ToEnum<T>(this string pEnumName)
        {
            if (Enum.IsDefined(typeof(T), pEnumName))
                return (T)Enum.Parse(typeof(T), pEnumName);
            else
                return default(T);
        }

        public static T GetValue<T>(this Enum pEnumItem)
        {
            return (T)Convert.ChangeType(pEnumItem, typeof(T));
        }
    }
}
